package com.vertx.web.explain;

import com.vertx.core.beam.AbstractBeanFactory;
import com.vertx.core.beam.BeanContainer;
import com.vertx.web.annotation.RequestMethod;
import com.vertx.web.annotation.RestApi;
import io.vertx.core.Vertx;
import io.vertx.ext.web.Router;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 描述:处理请求注入
 * 创建人:hzw
 * 创建时间: 2018/4/18 9:15
 **/
public class RestApiAnnotationExplain extends AbstractMethodAnnotationExplain {

    @Override
    public void handler(BeanContainer beanContainer, Method method, Annotation annotation, AbstractBeanFactory beanFactory, Object[] params) throws Exception {
        Router router = (Router) params[0];
        Vertx vertx=(Vertx)params[1];
        RestApi restApi=(RestApi)annotation;
        String path = getMapperPath(beanContainer.getBeanClass(),restApi.path());
        if (path != null) {
            if(restApi.method()[0]==RequestMethod.GET){
                router.get(path).handler(context -> {
                    try {
                        method.invoke(beanContainer.getBean(),context,vertx);
                    } catch (IllegalAccessException | InvocationTargetException e) {
                        e.printStackTrace();
                    }
                });
            }else if(restApi.method()[0]==RequestMethod.POST){
                router.post(path).handler(context -> {
                    try {
                        method.invoke(beanContainer.getBean(), context,vertx);
                    } catch (IllegalAccessException | InvocationTargetException e) {
                        e.printStackTrace();
                    }
                });
            }else if(restApi.method()[0]==RequestMethod.PUT){
                router.put(path).handler(context -> {
                    try {
                        method.invoke(beanContainer.getBean(), context,vertx);
                    } catch (IllegalAccessException | InvocationTargetException e) {
                        e.printStackTrace();
                    }
                });
            } else if (restApi.method()[0]==RequestMethod.DELETE) {
                router.delete(path).handler(context -> {
                    try {
                        method.invoke(beanContainer.getBean(), context,vertx);
                    } catch (IllegalAccessException | InvocationTargetException e) {
                        e.printStackTrace();
                    }
                });
            }
        }
    }

    @Override
    public Annotation getExplainClass() {
        return ()-> RestApi.class;
    }
}
